package gripper.ftp.prop;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropManager {
	Properties prop;
	public Map<String,User> usersMap;
	public PropManager() throws FileNotFoundException, IOException{
		prop=new Properties();
		prop.load(new FileInputStream("ftp.properties"));
		String users=prop.getProperty("users");
		String[] usersArray=users.split(",");
		loadUsers(usersArray);
	}
	public PropManager(String userName, String password, String path) {
		prop=new Properties();
		usersMap=new HashMap<String,User>();
		User user=new User();
		user.setName(userName);
		user.setRootDir(path);
		user.setPass(password);
		user.setEnable(true);
		user.setWrite(true);
		user.setDel(true);
		usersMap.put(userName, user);
	}
	public PropManager(User[] users) {
		prop=new Properties();
		usersMap=new HashMap<String,User>();
		for(User u:users){
			usersMap.put(u.getName(), u);
		}
	}
	private void loadUsers(String[] usersArray){
		usersMap=new HashMap<String,User>();
		if(usersArray==null){
			return;
		}
		for(String u:usersArray){
			loadUser(u);
		}
	}
	private void loadUser(String userName) {
		if(userName==null){
			return;
		}
		if(userName.trim().equals("")){
			return;
		}
		User user=new User();
		user.setName(userName);
		String pass=prop.getProperty(userName+".pass");
		user.setPass(pass);
		String dir=prop.getProperty(userName+".dir");
		user.setRootDir(dir);
		String write=prop.getProperty(userName+".write");
		user.setWrite(Boolean.getBoolean(write));
		String del=prop.getProperty(userName+".del");
		user.setDel(Boolean.getBoolean(del));
		usersMap.put(userName,user);
	}
	public void save(){
		try {
			prop.store(new FileOutputStream("ftp.properties"),"##");
		} catch (FileNotFoundException e) {
			Path path = Paths.get("ftp.properties");
			try {
				Files.createFile(path);
				prop.store(new FileOutputStream("ftp.properties"),"##");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
